var spawn = require('child_process').spawn;
var path = require('path');

var getResultFromData = function (data) {
  var reg = /^cout<<([\S\s]+)<<endl;$/;
  var result = data.match(reg);

  console.log(data,result);

  if(result){
    return result[1];
  }
};

module.exports = function (args,callback) {

  var phantom = spawn('phantomjs',args,{
    cwd:path.resolve(__dirname,'../')
  });


  var phantomResult = false;

  phantom.stdout.on('data', function (data) {
    data = data.toString().trim();
    console.log(data);
    console.log('============================');

    if(!phantomResult){
      phantomResult = getResultFromData(data);
      console.log('phantomResult:',phantomResult);
    }
    if(phantomResult){
      phantomResult = JSON.parse(phantomResult);
      phantom.kill();
    }
  });

  phantom.on('close', function (code,signal) {
    console.log(' exit at ',code,signal);

    callback && callback(phantomResult)
  })
};